package xyz.lwm.lazycat.netpipe.configure;

import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.beans.BeanLifecycle;
import xyz.lwm.lazycat.netpipe.domain.entity.User;
import xyz.lwm.lazycat.netpipe.service.UserService;
import xyz.lwm.lazycat.netpipe.setting.AuthSetting;
import xyz.lwm.lazycat.netpipe.util.SecureCredentialGenerator;

/**
 * 随机用户生成
 *
 * @author lwm
 */
@Bean
public class RandomUserGenerator implements BeanLifecycle {

    private static final String RANDOM_USER_FIXED_ID = "0";

    private static final String RANDOM_USER_NICK_NAME = "随机用户";

    private final AuthSetting authSetting;

    private final UserService userService;

    public RandomUserGenerator(AuthSetting authSetting, UserService userService) {
        this.authSetting = authSetting;
        this.userService = userService;
    }

    @Override
    public void postAllConstruct() {
        if (authSetting.isGenerateUser()) {

            // 生成8位用户名
            String username = SecureCredentialGenerator.generateUsername(8);
            // 生成12位密码
            String password = SecureCredentialGenerator.generatePassword(12);

            System.out.println("可登录用户名: " + username);
            System.out.println("可登录用户密码: " + password);

            // 随机用户
            User randomUser = new User();
            randomUser.setId(RANDOM_USER_FIXED_ID);
            randomUser.setUsername(username);
            randomUser.setPassword(password);
            randomUser.setNickName(RANDOM_USER_NICK_NAME);

            User user = userService.getById(RANDOM_USER_FIXED_ID);
            if (user == null) {
                userService.save(randomUser);
            } else {
                userService.updateById(randomUser);
            }

        }
    }

}
